package com.ril.financial.writers;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import com.csvreader.CsvWriter;
import com.ril.DateUtil;
import com.ril.financial.model.Transaction;
import com.ril.financial.model.TransactionCollection;
import com.ril.financial.parsers.HsbcCreditParser;
import org.apache.log4j.Logger;

public class TransactionListWriter {
    public TransactionCollection<Transaction> transactions;
    static Logger logger = Logger.getLogger(HsbcCreditParser.class);

    public TransactionListWriter(TransactionCollection<Transaction> transactions) {
        this.transactions = transactions;
    }

    public void writeToFile(String filename) {

        if (transactions == null || transactions.size() == 0) {
            logger.error(" no transactions to write");
            return;
        }

        boolean alreadyExists = new File(filename).exists();
        try {
            CsvWriter csvOutput = new CsvWriter(new FileWriter(filename, true), ',');

            if (!alreadyExists) {
                csvOutput.write("date");
                csvOutput.write("label");
                csvOutput.write("amount");
                csvOutput.endRecord();
            }

            for (Transaction transaction : transactions) {
                csvOutput.write(DateUtil.formatIsoDate(transaction.date));
                csvOutput.write(transaction.label);
                csvOutput.write(transaction.amount.toPlainString());
                csvOutput.endRecord();
            }

            csvOutput.close();
        } catch (IOException e) {
            logger.error(e);
        }
    }
}
